<template>
  <div class='container'>
    <el-card class="box-card">
      <div slot="header">
        {{$route.query.id?'试题修改':'试题录入'}}
      </div>

      <div class="el-card-body">
        <el-form :model="ruleForm"  :rules="rules" ref="ruleForm" label-width="120px">

          <el-form-item label="学科:" prop="subjectID">
            <el-select v-model="ruleForm.subjectID" @change="changeSubjects" placeholder="请选择学科" style="width:400px">
              <el-option
                v-for="item in subjectOptions"
                :key="item.value"
                :label="item.label" 
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="目录:" prop="catalogID">
            <el-select v-model="ruleForm.catalogID" placeholder="请选择目录" style="width:400px">
              <el-option
                v-for="item in catalogOptions"
                :key="item.id"
                :label="item.directoryName" 
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="企业:" prop="enterpriseID">
            <el-select v-model="ruleForm.enterpriseID" placeholder="请选择企业" style="width:400px">
              <el-option
                v-for="item in enterpriseOptions"
                :key="item.id"
                :label="item.company" 
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="城市:" prop="city">
            <el-select v-model="ruleForm.province" @change="getAreaOptions" placeholder="请选择城市" style="width:195px;margin-right: 10px">
              <el-option
                v-for="item in cityOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select v-model="ruleForm.city" placeholder="请选择区域" style="width:195px">
              <el-option
                v-for="item in areaOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="方向:" prop="direction">
            <el-select v-model="ruleForm.direction" placeholder="请选择方向" style="width:400px">
              <el-option
                v-for="item in directionOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="ruleForm.questionType">
              <el-radio v-for="item in questionType" :key="item.value" :label="item.value+''">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="ruleForm.difficulty">
              <el-radio v-for="item in difficulty" :key="item.value" :label="item.value+''">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="题干:" prop="question">
            <quill-editor v-model="ruleForm.question" :options="editorOptions"></quill-editor>
          </el-form-item>

          <el-form-item label="选项:" prop="options" v-if="ruleForm.questionType!=='3'" style="margin-top:80px">
            <div class="option_item" v-for="item in ruleForm.options" :key="item.code">
              <el-radio v-if="ruleForm.questionType==='1'"  @change="changeRadio(item)" v-model="item.isRight" style="margin-right:0" :label="true">{{item.code}}：</el-radio>
              <el-checkbox v-if="ruleForm.questionType==='2'" v-model="item.isRight" style="margin-right:0" :label="true">{{item.code}}：</el-checkbox>
              <el-input v-model="item.title" style="width:240px"></el-input>
              <el-upload
                style="margin-left:4px"
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :headers="{'Authorization':'Bearer '+ token}"
                :on-success="(res,file)=>{uploadSuccess(item,file)}"
                :show-file-list="false">
                <img v-if="item.img" :src="item.img" class="avatar">
                <span v-else>上传图片</span>
                <i class="el-icon-circle-close"></i>
              </el-upload>
            </div>
            <el-button type="danger" @click="addOptions" :disabled="ruleForm.questionType!=='2'" size="small">+增加选项与答案</el-button>
          </el-form-item>

          <el-form-item label="解析视频:">
            <el-input style="width:400px" v-model="ruleForm.videoURL"></el-input>
          </el-form-item>

          <el-form-item label="答案解析:" prop="question">
            <quill-editor v-model="ruleForm.answer" :options="editorOptions"/>
          </el-form-item>

          <el-form-item label="题目备注:" style="margin-top:80px">
            <el-input
              type="textarea"
              :rows="4"
              v-model="ruleForm.remarks"
              style="width:400px"
            >
            </el-input>
          </el-form-item>

          <el-form-item label="试题标签:">
            <el-select 
              v-model="ruleForm.tags" 
              placeholder="请选择试题标签" 
              style="width:400px"
              multiple
              filterable
              allow-create
              default-first-option
            >
              <el-option
                v-for="item in tagsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button v-if="!$route.query.id" @click="submit()" type="primary">确认提交</el-button>
            <el-button v-else @click="updata()" type="primary">确认提交</el-button>
          </el-form-item>

        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import {simple as getSubjects} from '@/api/hmmm/subjects'
import {list as getCompanys} from '@/api/hmmm/companys'
import {list as getDirectorys} from '@/api/hmmm/directorys'
import { simple as getTags } from '@/api/hmmm/tags'
import {difficulty,questionType,direction} from '@/api/hmmm/constants'
import {provinces,citys} from '@/api/hmmm/citys'
import {add,update,detail} from '@/api/hmmm/questions'

//富文本编辑器
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

import { getToken } from '@/utils/auth'
export default {
  components:{
    quillEditor
  },
  data() {
    return {
      token: getToken(),
      editorOptions: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        },
        placeholder: ''
      },

      subjectOptions:[],
      catalogOptions:[],
      enterpriseOptions:[],
      cityOptions:provinces(),
      areaOptions:[],
      directionOptions:direction,
      questionType,
      difficulty,
      tagsOptions:[],

      ruleForm: {
        subjectID:'',
        catalogID:'',
        enterpriseID:'',
        direction:'',
        province:'',
        city:'',
        questionType:'1',
        difficulty:'1',
        question:'',
        options:[
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },

      //校验规则
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请选择题干', trigger: 'change' }
        ]
      }
    }
  },
  created(){
    this.getSubjectOptions()
    this.getEnterpriseOptions()
    if(this.$route.query.id){
      this.getQuestion()
    }
  },
  watch: {
    '$route.query': function () {
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.ruleForm = {
          subjectID: null,
          catalogID: null,
          enterpriseID: null,
          province: null,
          city: null,
          direction: null,
          questionType: '1',
          difficulty: '1',
          question: null,
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  methods: {
    async getSubjectOptions () {
      const res = await getSubjects()
      this.subjectOptions = res.data
    },

    async getEnterpriseOptions(){
      const res = await getCompanys()
      this.enterpriseOptions = res.data.items
    },

    getAreaOptions (cityName) {
      this.ruleForm.city = null
      this.areaOptions = citys(cityName)
    },

    async changeSubjects (subjectID) {
      this.ruleForm.catalogID = null
      const res = await getDirectorys({ subjectID: this.ruleForm.subjectID })
      this.catalogOptions = res.data.items
      this.ruleForm.tags = null
      const res1 = await getTags({ subjectID: this.ruleForm.subjectID })
      this.tagsOptions = res1.data
    },

    changeRadio (item) {
      this.ruleForm.options.forEach(item => {
        item.isRight = false
      })
      item.isRight = true
    },

    addOptions(){
      this.ruleForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.ruleForm.options.length),
        title: '',
        img: ''
      })
    },

    uploadSuccess(item,file){
      item.img = URL.createObjectURL(file.raw)
    },

    submit(){
      this.$refs.ruleForm.validate(async valid => {
        try{
          if (valid) {
            const data={...this.ruleForm}
            if(data.tags){
              data.tags=data.tags.join(',')
            }
            await add(data)
            this.$message.success('添加成功')
            this.$router.push('/questions/list')
          }
        } catch(err){
          console.log(err);
        }
      })
    },

    async getQuestion(){
      const {data}=await detail({ id: this.$route.query.id })
      if(data.tags){
        data.tags = data.tags.split(',')
      }
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.ruleForm=data
      const res1 = await  getDirectorys({ subjectID: this.ruleForm.subjectID })
      this.catalogOptions = res1.data
      const res2 = await getTags({ subjectID: this.ruleForm.subjectID })
      this.tagsOptions = res2.data
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },

    updata(){
      this.$refs.ruleForm.validate(async valid => {
        try{
          if (valid) {
            const data={...this.ruleForm}
            if(data.tags){
              data.tags=data.tags.join(',')
            }
            await update(data)
            this.$message.success('修改成功')
            this.$router.push('/questions/list')
          }
        } catch(err){
          console.log(err);
        }
      })
    },
  }
}
</script>

<style scoped lang='less'>
  .container{
    .el-card{
      margin: 18px 20px;
    }
    .quill-editor{
      height: 150px;
    }
    .avatar-uploader{
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      width: 100px;
      height: 60px;
      line-height: 60px;
      display: inline-block;
      text-align: center;
      margin-bottom: 8px;
      i{
        position: absolute;
        right: 0;
        top: 0;
        transform: translate(50%,-50%);
        background: #fff;
        font-size: 18px;
        color: #999;
      }
      .avatar {
        width: 100px;
        height: 60px;
        display: block;
        overflow: hidden;
      }
    }
  }
</style>
